<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="100px" inline>
      <el-form-item label="工作站名称">
        <el-input v-model="searchForm.workstationName" placeholder="工作站名称" clearable />
      </el-form-item>
      <el-form-item label="生产工单编码">
        <el-input v-model="searchForm.productionOrderCode" placeholder="生产工单编码" clearable />
      </el-form-item>
      <el-form-item label="报工类型">
        <el-select style="width: 120px" clearable v-model="searchForm.type" placeholder="报工类型">
          <el-option
              v-for="dictData in workReportTypeDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品物料编号" >
        <el-input v-model="searchForm.materialCode" placeholder="产品物料编号" clearable />
      </el-form-item>
      <el-form-item label="产品物料名称">
        <el-input v-model="searchForm.materialName" placeholder="产品物料名称" clearable />
      </el-form-item>
      <el-form-item label="报工人">
        <el-select style="width: 120px;" v-model="searchForm.submitBy" placeholder="报工人" clearable>
          <el-option
              v-for="user in sysUserList"
              :label="user.fullName"
              :value="user.id"
              :key="user.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="报工状态">
        <el-select style="width: 120px;" v-model="searchForm.status" placeholder="报工状态" clearable>
          <el-option
              v-for="dictData in workReportStatusDictDataList"
              :value="dictData.id"
              :label="dictData.dictLabel"
              :key="dictData.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button  type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 工具栏 -->
  <div class="toolbar">
    <el-button type="success" @click="handleAdd" >新增报工</el-button>
    <el-button type="danger" @click="handleBatchDelete" :disabled="selectedList.length === 0">删除报工</el-button>
  </div>
  <!-- 列表 -->
  <el-card class="table-card">
    <el-table
        :data="workReportList"
        border
        stripe
        @selection-change = "selectedWorkReport"
    >
      <el-table-column type="selection" />
      <el-table-column prop="code" label="报工编号">
        <template #default="scope">
          <el-link type="primary" @click="previewProductionReport(scope.row)">{{scope.row.code}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="typeDictData.dictLabel" label="报工类型"/>
      <el-table-column prop="workstationName" label="工作站"/>
      <el-table-column prop="process.processName" label="工序"/>
      <el-table-column prop="productionOrderCode" label="工单编号"/>
      <el-table-column prop="materialCode" label="产品物料编号"/>
      <el-table-column prop="materialName" label="产品物料名称"/>
      <el-table-column prop="material.specification" label="规格型号"/>
      <el-table-column prop="material.unit.name" label="单位"/>
      <el-table-column prop="workReportQuantity" label="报工数量"/>
      <el-table-column prop="submitUser.fullName" label="报工人"/>
      <el-table-column prop="reportTime" label="报工时间"/>
      <el-table-column prop="checkUser.fullName" label="审核人"/>
      <el-table-column prop="statusDictData.dictLabel" label="状态">
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" v-if="scope.row.statusDictData.dictValue == 1" @click="updateProductionOrderView(scope.row)">编辑</el-button>
          <el-button size="small" v-if="scope.row.statusDictData.dictValue == 2" @click="checkWorkReport(scope.row)">审核</el-button>
          <el-button size="small" type="primary" @click="previewProductionOrder(scope.row)">预览</el-button>
          <el-button
              v-if="scope.row.statusDictData.dictValue == 1" size="small" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!--   分页栏     -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 其他弹窗 -->
  <el-dialog
      :title="dialogTitle"
      v-model="addOrUpdateDialogVisable"
      width="80%">
    <el-form v-model="workReportForm" >
      <!-- 第一行：报工编号 + 报工类型 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <el-row>
              <el-col :span="20">
                <el-form-item label="报工编号" >
                <el-input  :disabled="isDetail" v-model="workReportForm.code" placeholder="请输入报工编号" />
                </el-form-item>
              </el-col >
              <el-col :span="2">
                <el-switch   :disabled="isDetail" @click="autoCode" inline-prompt active-text="自动生成" inactive-text="自动生成" v-model="isAutoCode" />
              </el-col>
          </el-row>
        </el-col>

        <el-col :span="8">
          <el-form-item label="报工类型">
            <el-select style="width: 120px" clearable v-model="workReportForm.type" placeholder="报工类型">
              <el-option
                  v-for="dictData in workReportTypeDictDataList"
                  :value="dictData.id"
                  :label="dictData.dictLabel"
                  :key="dictData.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：生产任务 + 生产工单 + 工作站  -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item  label="生产任务" >
            <el-input v-model="workReportForm.taskCode" placeholder="请选择任务" :disabled="isDetail" >
              <template #append>
                <el-button  @click="selectTask"  :disabled="isDetail"><el-icon><Search/></el-icon></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产工单" >
            <el-input v-model="workReportForm.productionOrderCode" placeholder="请选择任务" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作站" >
            <el-input v-model="workReportForm.workstationName" placeholder="请选择任务" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行：产品编码 + 产品名称 + 产品单位-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="产品编码" >
            <el-input v-model="workReportForm.materialCode" placeholder="请选择任务" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品名称" >
            <el-input v-model="workReportForm.material.name" placeholder="请选择任务" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品单位" >
            <el-input v-model="workReportForm.material.unit.name" placeholder="请选择任务" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第四行：规格型号 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="规格型号" >
            <el-input
                v-model="workReportForm.material.specification"
                type="textarea"
                disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第五行：报工数量 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="报工数量" >
            <el-input-number v-model="workReportForm.workReportQuantity" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 第六行：报工人 + 报工时间 + 审核人 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="报工人" >
            <el-input v-model="workReportForm.submitUser.fullName"  :disabled="isDetail" placeholder="请输入报工人" >
              <template #append>
                <el-button  @click="selectSubmitUser"  :disabled="isDetail"><el-icon><Search/></el-icon></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="需求日期" >
            <el-date-picker
                v-model="workReportForm.reportTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择需求日期"
                :disabled="isDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核人" >
            <el-input v-model="workReportForm.checkUser.fullName" placeholder="请输入审核人" :disabled="isDetail" >
              <template #append>
                <el-button  @click="selectCheckUser"  :disabled="isDetail"><el-icon><Search/></el-icon></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行：备注 -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" >
            <el-input
                v-model="workReportForm.remark"
                type="textarea"
                placeholder="请输入内容"
                :disabled="isDetail"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddOrUpdate">取消</el-button>
        <el-button v-if="isCheck" @click="checkFail">审核不通过</el-button>
        <el-button v-if="isEdit||isCheck" @click="confirmWorkOrder" type="success">确认</el-button>
        <el-button v-if="isEdit||isAdd"  type="primary" @click="submitWorkOrderForm">保存</el-button>

      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="selectCheckUserVisable" title="选择审核人" width="80%">
    <user-list @select-user ="handleSelectCheckUser"/>
  </el-dialog>
  <el-dialog v-model="selectSubmitUserVisable" title="选择报工人" width="80%">
    <user-list @select-user ="handleSelectSubmitUser"/>
  </el-dialog>
  <el-dialog v-model="selectTaskVisable" title="选择任务" width="80%">
    <task-list @select-task = "handleTask"/>
  </el-dialog>
</template>


<script setup>
// 导入必须的内容
import {ref,onMounted} from "vue";
import {ElMessage,ElMessageBox} from "element-plus";
import {getCodeAuto} from "@/api/codeAuto.js"
import {getUserList} from "@/api/user.js"
import {getUserById} from "@/api/sysUser.js"
import {queryTaskByCode} from "@/api/task.js"
import {queryById} from "@/api/production-order.js"
import {getWorkstationByCode} from "@/api/workstation.js"
import {getWorkReportList,queryWorkReportById,updateWorkReport,addWorkReport,deleteWorkReport,batchDeleteWorkReport} from "@/api/workReport.js"
// 导入字典相关的API
import Bom from "@/views/pro/production-order/Bom.vue";
import {getDictDataList,getDictDataById} from "@/api/dictData.js";
import CustomerList from "@/views/pro/production-order/customer-list.vue";
import {Search} from "@element-plus/icons-vue";
import UserList from "@/views/pro/feedback/user-list.vue";
import TaskList from "@/views/pro/feedback/task-list.vue";


// ----- 属性声明 ↓
//已选择的报工列表
const selectedList = ref([])
//
const isAutoCode = ref(false)
// 绑定搜索表单的数据
const searchForm = ref({
  productionOrderCode:"",
  materialCode:"",
  materialName:"",
  workstationName:"",
  type:"",
  submitBy:"",
  status:"",
})
// 报工列表数据
const workReportList = ref([])
// 分页相关数据
const pagination = ref({
  currentPage:1,
  pageSize:10,
  total:0
})
// 弹窗的标题
const dialogTitle = ref("添加生产工单");
// 弹窗标记
const addOrUpdateDialogVisable = ref(false);
// 编辑标记
const isEdit = ref(false);
// 新增/编辑表单的数据绑定对象
const workReportForm = ref({
  id:"",
  productionOrderCode:"",
  materialCode:"",
  materialName:"",
  workstationName:"",
  taskCode:"",
  code:"",
  type:"",
  submitBy:"",
  checkBy:"",
  status:"",
  workReportQuantity:"",
  reportTime:"",
  remark:"",
  typeDictData:{dictLabel:""},
  material:{unit:{name:""},specification:"",name:""},
  submitUser:{fullName:""},
  checkUser:{fullName:""},
  statusDictData:{dictLabel:""}
})

// 是否是显示详情的标记
const isDetail = ref(false);

// 报工类型字典列表
const workReportTypeDictDataList = ref([]);
// 报工状态点列表
const workReportStatusDictDataList= ref([]);
//员工列表
const sysUserList = ref([]);
//选择审核人弹窗
const selectCheckUserVisable = ref(false)
//选择报工人弹窗
const selectSubmitUserVisable = ref(false)
//选择任务弹窗
const selectTaskVisable = ref(false)
//确认工单/审核工单标识
const isConfirm = ref(false)
//审核标记
const isCheck = ref(false)
const isAdd = ref(false)
// ----- 属性声明 ↑
// -- 函数声明 ↓
//选择任务
const selectTask = ()=>{
  selectTaskVisable.value = true;
}
//处理选择的任务
const handleTask = (taskCode)=>{
  workReportForm.value.taskCode = taskCode;
  queryTaskByCode(taskCode).then(res =>{
    let productionOrderId = res.data.productionOrderId;
    let workstationCode = res.data.workstationCode
    getWorkstationByCode(workstationCode).then(res =>{
      workReportForm.value.workstationName = res.data.name;
    })
    queryById(productionOrderId).then(res =>{
      workReportForm.value.productionOrderCode = res.data.productionOrderCode
      workReportForm.value.materialCode = res.data.materialCode
      workReportForm.value.material = res.data.material
    })
  })
  selectTaskVisable.value = false;
}
const selectSubmitUser = ()=>{
  selectSubmitUserVisable.value = true;
}
//选择审核人按钮
const selectCheckUser = ()=>{
  selectCheckUserVisable.value = true;
}
//选择报工人
const handleSelectSubmitUser = (userId) =>{
  workReportForm.value.submitBy = userId
  getUserById(userId).then(res =>{
    workReportForm.value.submitUser = res.data;
  })
  selectSubmitUserVisable.value = false;
}
//选择审核人
const handleSelectCheckUser = (userId)=>{
    workReportForm.value.checkBy = userId
    getUserById(userId).then(res =>{
      workReportForm.value.checkUser = res.data;
    })
    selectCheckUserVisable.value = false;
}
//选择工单
const selectedWorkReport = (selection)=>{
  selectedList.value = selection;
  console.log(selectedList.value)
}
//审核不通过
const checkFail = ()=>{
  let status = workReportForm.value.status
  workReportForm.value.status = status - 1 ;
  ElMessageBox.confirm(
      `工单 "${workReportForm.value.code}" 审核不通过？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then( ()=>{
    updateWorkReport(workReportForm.value).then(res =>{
      if (res.code === 200){
        handleSearch();
        ElMessage.success(res.msg)
      }else {
        ElMessage.error(res.msg)
      }
    })
    cancelAddOrUpdate();
  }).catch( ()=>{
    ElMessage.info("取消报工审核")
  })
}
//审核按钮事件
const checkWorkReport = (row)=>{
  isCheck.value = true;
  queryWorkReportById(row.id).then(res =>{
    workReportForm.value = res.data
  })
  dialogTitle.value = "审核报工"
  addOrUpdateDialogVisable.value = true
}
//确认按钮，确认报工，改变报工状态
const confirmWorkOrder = ()=>{
  isConfirm.value = true;
  let status = workReportForm.value.status
  workReportForm.value.status = status + 1 ;
  ElMessageBox.confirm(
      `工单 "${workReportForm.value.code}" 是否通过确认？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then( ()=>{
    updateWorkReport(workReportForm.value).then(res =>{
      if (res.code === 200){
        handleSearch();
        ElMessage.success(res.msg)
      }else {
        ElMessage.error(res.msg)
      }
    })
    cancelAddOrUpdate();
  }).catch( ()=>{
    ElMessage.info("取消确认工单")
  })
}


//编辑按钮事件
const updateProductionOrderView =(row)=>{
  isConfirm.value = true;
  isEdit.value  = true;
  queryWorkReportById(row.id).then(res =>{
    workReportForm.value = res.data
  })
  dialogTitle.value = "编辑报工"
  addOrUpdateDialogVisable.value = true
}
//预览工单
const previewProductionReport = (row)=>{
  dialogTitle.value = "预览工单"
  isDetail.value = true;
  queryWorkReportById(row.id).then(res=>{
    workReportForm.value = res.data
    addOrUpdateDialogVisable.value = true;
  })
}
//删除按钮
const handleDelete = (row)=>{
  ElMessageBox.confirm(
      `工单 "${row.code}" 是否要删除？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then( ()=>{
    deleteWorkReport(row.id).then(res =>{
     if (res.code === 200){
       handleSearch();
       ElMessage.success(res.msg);
     }else {
       ElMessage.error(res.msg);
     }
    })
  }).catch( ()=>{
      ElMessage.info("取消删除")
  })
}
//批量删除
const handleBatchDelete = ()=>{
  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedList.value.length} 个报工吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    let param = '';
    selectedList.value.forEach(item => {
      param += "id=" + item.id + "&";
    })
    param = param.substring(0, param.length - 1);
    batchDeleteWorkReport(param).then(res=>{
      if (res.code==200){
        ElMessage.success('批量删除成功')
        handleSearch();
      }else {
        ElMessage.error('批量删除失败')
      }
    })
    selectedList.value = []
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}


//重置查询表单
const resetSearch = ()=>{
  searchForm.value ={
    productionOrderCode:"",
    materialCode:"",
    materialName:"",
    workstationName:"",
    type:"",
    submitBy:"",
    status:"",
  }
}
const loadWorkReportStatusDictDataList=()=>{
  getDictDataList({dictType:"work_report_status"}).then(res=>{
    workReportStatusDictDataList.value = res.data.records;
  })
}
//加载报工类型字典的函数
const loadWorkReportTypeDictDataList = ()=>{
  getDictDataList({dictType:"work_report_type"}).then(res=>{
    workReportTypeDictDataList.value = res.data.records;
  })
}
// 加载员工函数
const loadUserList=()=>{
  let params = {}
  params.pageNum = 1;
  params.size = 10000;
  getUserList(params).then(res =>{
    sysUserList.value = res.data
  })
}
//修改工单状态，确认工单/审核工单

// 提交新增/编辑审核表单的按钮事件
const submitWorkOrderForm = ()=>{
  console.log(isEdit.value)
  if (isEdit.value){
    updateWorkReport(workReportForm.value).then(res=>{
      if (res.code === 200){
        handleSearch();
        ElMessage.success(res.msg)
      }else {
        ElMessage.error(res.msg)
      }
    })
  }else {
    addWorkReport(workReportForm.value).then(res=>{
      if (res.code === 200){
        handleSearch();
        ElMessage.success(res.msg)
      }else {
        ElMessage.error(res.msg)
      }
    })
  }
  cancelAddOrUpdate();
}
// 取消新增/编辑的事件
const cancelAddOrUpdate = ()=>{
  isCheck.value = false;
  isAdd.value = false;
  isEdit.value = false;
  isConfirm.value = false;
  isDetail.value = false;
  dialogTitle.value = "添加生产工单"
  addOrUpdateDialogVisable.value = false;
  workReportForm.value = {
    id:"",
    productionOrderCode:"",
    materialCode:"",
    materialName:"",
    workstationName:"",
    taskCode:"",
    code:"",
    type:"",
    submitBy:"",
    checkBy:"",
    status:"",
    workReportQuantity:"",
    reportTime:"",
    remark:"",
    typeDictData:{dictLabel:""},
    material:{unit:{name:""},specification:""},
    submitUser:{fullName:""},
    checkUser:{fullName:""},
    statusDictData:{dictLabel:""}
  }

}
// 自动生成编号的事件
const autoCode = ()=>{
  if (isAutoCode.value){
    getCodeAuto("TASK_CODE").then(res =>{
      if (res.code === 200){
        workReportForm.value.code = res.data
      }else {
        isAutoCode.value = false
        ElMessage.error("编码生成失败")
      }
    })
  }else {
    workReportForm.value.code = ""
  }
}
// 新增工单的按钮事件
const handleAdd = ()=>{
  isAdd.value = true;
  addOrUpdateDialogVisable.value = true;

}
// 改变了每页大小的事件
const handleSizeChange =(pageSize)=>{
  pagination.value.pageSize = pageSize;
  handleSearch();
}
// 改变页面的事件  翻页事件
const handleCurrentChange =(newPage)=>{
  pagination.value.currentPage = newPage;
  handleSearch();
}
// 搜索数据的事件
const handleSearch=()=> {
  // 调用查询的接口查询数据
  let params = {};// 这里需要组织参数--------------
  // 请求参数就是searchForm.vaue 和  page相关的参数
  params = searchForm.value;// 这里只包含了搜索条件，没有分页参数
  params.pageNum = pagination.value.currentPage;
  params.pageSize = pagination.value.pageSize;
  getWorkReportList(params).then(res=>{
    workReportList.value = res.data.list;
    pagination.value.total = res.data.total;
    console.log("workReportList:")
    console.log(workReportList.value)
  })

}
// -- 函数声明 ↑
onMounted(()=>{
  handleSearch();
  loadWorkReportStatusDictDataList();
  loadWorkReportTypeDictDataList();
  loadUserList();
})


</script>

<style scoped>
.customer-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>